#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"


void HeapInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void swap(HPDataType* x, HPDataType* y)
{
	HPDataType* tmp = *x;
	*x = *y;
	*y = tmp;
}
void AdjustUp(HPDataType* a, int Child)
{
	int parent = (Child - 1) / 2;
	while (Child > 0)
	{
		int parent = (Child - 1) / 2;
		if (a[parent] > a[Child])
		{
			swap(&a[parent], &a[Child]);
			Child = parent;
			parent = (Child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void AdjustDown(HPDataType* a, int size, int parent)
{
	int child = 2 * parent + 1;
	while (child < size)
	{
		if (child+1 < size && a[child + 1] < a[child])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			swap(&(a[child]), &(a[parent]));
			parent = child;
			child = parent * 2 + 1;

		}
		else
		{
			break;
		}
	}
}
void HeapDestroy(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void HeapPush(HP* php, HPDataType x)
{
	if (php->capacity == php->size)
	{
		HPDataType* tmp = NULL;
		int newCapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		tmp = (HPDataType*)realloc(php->a, sizeof(HPDataType) * newCapacity);
		if (tmp == NULL)
		{
			perror("realloc failed");
			exit(-1);
		}
		php->a = tmp;
		php->capacity = newCapacity;
	}
	php->a[php->size] = x;
	php->size++;
	AdjustUp(php->a, php->size - 1);
}

void HeapPop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	swap(&(php->a[0]), &(php->a[php->size-1]));
	php->size--;

	AdjustDown(php->a, php->size - 1, 0);

}

bool HeapEmpty(HP* php)
{
	assert(php);
	assert(php->size > 0);
	return php->size == 0;
}

int HeapSize(HP* php)
{
	assert(php);
	return php->size;
}

HPDataType HeapTop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	return php->a[0];
}

void HeapPrint(HP* php)
{
	assert(php);
	int i = 0;
	for (i = 0; i < php->size; i++)
	{
		printf("%d ", php->a[i]);
	}
	printf("\n");
}